/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package control.user;

import control.admin.CoolServlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import persistence.PersistenceFactory;
import persistence.PersistenceInterface;

/**
 *
 * @author isen
 */
public class AddProductToCartServlet extends CoolServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            generateShoppingCartFromRequest(request);
            gotoURL(successForm, request, response);
        } catch (Exception e) {
            request.setAttribute("resultado", "Error to add a product");
            request.getRequestDispatcher("forms/addProductToACaddy.jsp").forward(request, response);
        }
    }

    void generateShoppingCartFromRequest(HttpServletRequest request) throws Exception {

        PersistenceInterface persistenceManager = PersistenceFactory.getInstance(persistenceMechanism);

        int currentid;
        int newamount;
        String clientname = (String) request.getSession().getAttribute("user");

        String[] products = request.getParameterValues("productname");

        String[] quantities = request.getParameterValues("quantity");
        int[] amount = new int[quantities.length];
        for (int i = 0; i < quantities.length; i++) {
            try {
                amount[i] = Integer.parseInt(quantities[i]);
            } catch (NumberFormatException ex) {
                amount[i] = 0;
            }
        }

        if (!isOnlyZero(amount)) {
            currentid = persistenceManager.getCurrentCartId(clientname);
      
            for (int j = 0; j < amount.length; j++) {
                if (persistenceManager.isAlreadyAdded(currentid, products[j])) {
                    newamount = amount[j] + persistenceManager.getAmountFromACart(currentid, products[j]);

                    if (newamount <= persistenceManager.getStock(products[j])) {
                        persistenceManager.updateQuantityOfACart(currentid, products[j], newamount);
                    } else {
                        request.setAttribute("resultado", "Sorry, but the amount you asked is superior at the amount in stock!");
                        throw new Exception();
                    }
                } else {
                    if (amount[j] <= persistenceManager.getStock(products[j])) {
                        persistenceManager.addProductToShoppingCart(products[j], amount[j], currentid);
                    } else {
                        request.setAttribute("resultado", "Sorry, but the amount you asked is superior at the amount in stock!");
                        throw new Exception();
                    }
                }
            }
        } else {
            request.setAttribute("resultado", "You have to select at least one article!");
            throw new Exception();
        }
    }

    boolean isOnlyZero(int[] amount) {
        int somme = 0;
        for (int i = 0; i < amount.length; i++) {
            somme = amount[i] + somme;
        }
        if (somme != 0) {
            return false;
        } else {
            return true;
        }
    }
    
    
    
}
